/*
 * AIEngine a new generation network intrusion detection system.
 *
 * Copyright (C) 2013-2023  Luis Campo Giralte
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 *
 * Written by Luis Campo Giralte <luis.camp0.2009@gmail.com>
 *
 */
#include "StringMap.h"

namespace aiengine {

void StringMap::sort(std::vector<PairStringCacheHits> &g_list) const {

        // Sort by using lambdas
        std::sort(
                g_list.begin(),
                g_list.end(),
                [] (PairStringCacheHits const &a, PairStringCacheHits const &b)
                {
			const StringCacheHits &h1 = a.second;
			const StringCacheHits &h2 = b.second;

                        return h1.hits > h2.hits;
        });
}

void StringMap::show(std::basic_ostream<char> &out, const char *tab, int32_t limit) const {

        out << tab << name_ << " usage" << "\n";

        std::vector<PairStringCacheHits> g_list(begin(), end());

	sort(g_list);

	uint32_t count = 0;
        for (auto it = g_list.begin(); it != g_list.end(); ++it) {
                SharedPointer<StringCache> uri = ((*it).second).sc;
                int hits = ((*it).second).hits;
                if (uri) {
			if (count >= limit) {
				out << tab << "\t...\n";
				break;
			}
			++ count;
			out << tab << "\t" << row_name_ << ":" << uri->name() <<":" << hits << "\n";
		}
        }
	out.flush();
}

void StringMap::show(Json &out, int32_t limit) const {

        std::vector<PairStringCacheHits> g_list(begin(), end());

	sort(g_list);

        uint32_t count = 0;
        for (auto it = g_list.begin(); it != g_list.end(); ++it) {
                SharedPointer<StringCache> uri = ((*it).second).sc;
                int hits = ((*it).second).hits;
                if (uri) {
                        if (count >= limit)
                                break;
                        ++ count;
                        out.emplace(uri->name(), hits);
                }
        }
}

} // namespace aiengine

